package spider

import (
	"asocrawler/conf"
	"asocrawler/db"
	"asocrawler/tool"
	"fmt"
	"log"
	"time"
)

type GooglePlaySpider struct {
	ChannelName  string
	TimeInterval int
	Platform     string
}

func NewGooglePlaySpider() (t *GooglePlaySpider) {
	t = &GooglePlaySpider{
		ChannelName:  "Google Play",
		TimeInterval: 2 * 60 * 60,
		Platform:     "Android",
	}
	return
}
func (this GooglePlaySpider) Run() {
	go func() {
		this.run()
	}()
}
func (this *GooglePlaySpider) Println(v ...interface{}) {
	var str = fmt.Sprintf("[%s]-[%s]", this.ChannelName, this.Platform)
	if conf.Conf.Debug.Switch {
		str += "-[Debug]"
	}
	log.Println(str, fmt.Sprintln(v...))
}

func (this *GooglePlaySpider) collect(date string) (bool, error) {

	err := db.SyncHkGoogleData(this.ChannelName, this.Platform, "", date)
	if err != nil {
		return false, err
	}
	return true, nil
}

func (this *GooglePlaySpider) run() {
	if conf.Conf.Debug.Switch {
		for _, fDate := range conf.Conf.Debug.DateList {
			this.Println("日期:", fDate, "开始采集数据...")
			succ, err := this.collect(fDate)
			if succ {
				this.Println("日期:", fDate, "采集数据完成")
			} else {
				if err == nil {
					this.Println("日期:", fDate, "数据未更新")
				} else {
					this.Println("日期:", fDate, "出现错误err:", err)
				}
			}
		}
	} else {
	re:
		fDate := time.Now().Format("2006-01-02")
		this.GetDataByDate(fDate)
		time.Sleep(time.Duration(this.TimeInterval) * time.Second)
		goto re
	}
}

func (this *GooglePlaySpider) GetDataByDate(date string) {
	this.Println("日期:", date, "开始采集数据...")
	succ, err := this.collect(date)
	if succ {
		this.Println("日期:", date, "采集数据完成 稍后再次采集...")
	} else {
		if err == nil {
			this.Println("日期:", date, "数据未更新 稍后重新采集...")
		} else {
			tool.SendWarn("ASO报警-Google爬虫报错", "ASO报警-Google爬虫报错,错误信息："+err.Error())
			this.Println("日期:", date, "出现错误err:", err, "稍后重新采集...")
		}
	}
}
